package com.edu.shiro.filter;

import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.edu.shiro.domain.SysUser;


/**
 * 自定义filter 实现并发人数控制
 */
public class KickoutSessionControlFilter extends AccessControlFilter{
	
	/*提出后到的地址 */
	private String kickoutUrl;
	
	/**踢出之前登陆的/之后登陆的用户  默认踢出之前登陆的用户 */
	private boolean kickoutAfter = false;
	
	 /**  同一个帐号最大会话数 默认1 */
    private int maxSession = 1;
    
    private SessionManager sessionManager;
    
    private Cache<String,Deque<Serializable>> cache;
    


	public void setKickoutUrl(String kickoutUrl) {
		this.kickoutUrl = kickoutUrl;
	}



	public void setKickoutAfter(boolean kickoutAfter) {
		this.kickoutAfter = kickoutAfter;
	}



	public void setMaxSession(int maxSession) {
		this.maxSession = maxSession;
	}


	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	public void setCache(CacheManager cacheManager) {
		this.cache = cacheManager.getCache("shiro-activeSessionCache");
	}
	
	/**
	 * 是否允许访问，true表示允许，
	 * false需要执行onAccessDenied 方法
	 * 
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		return false;
	}
	
	 /**
     * 表示访问拒绝时是否自己处理，如果返回true表示自己不处理且继续拦截器链执行，返回false表示自己已经处理了（比如重定向到另一个页面）。
     */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		//没有登陆执行后面的流程
		if(!subject.isAuthenticated() && !subject.isRemembered()){
			return true;
		}
		Session session = subject.getSession();
		//获取user实体，定义在UserRealm中的new SimpleAuthenticationInfo(user, password, getName()); 
		String username = ((SysUser)subject.getPrincipal()).getUserName();
		Serializable sessionId = session.getId();
		
		//初始化用户列队放到缓存中
		Deque<Serializable> deque = cache.get(username);
		if(deque == null){
			deque = new LinkedList<Serializable>();
			cache.put(username, deque);
		}
		//如果队列里没有sessionId,且用户没有被踢出；放入列队
		if(!deque.contains(sessionId) && session.getAttribute("kickout") == null){
			deque.push(sessionId);
		}
		
		//如果列队里的sessionId数超出最大会话数，开始踢人
		while(deque.size() > maxSession){
			Serializable kickoutSessionId = null;
			if(kickoutAfter){//如果踢后者
				kickoutSessionId = deque.getFirst();
				kickoutSessionId = deque.removeFirst();
			}else{
				kickoutSessionId = deque.removeLast();
			}
			
			try{
				Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
				if(kickoutSession != null){
					//设置会话kickout属性表示踢出了
					kickoutSession.setAttribute("kickout", true);
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		//如果被踢出了。直接退出，重定向到踢出后的地址
		if(session.getAttribute("kickout") != null){
			//会话被踢出了
			try{
				subject.logout();
			}catch (Exception e) {
				e.printStackTrace();
			}
			WebUtils.issueRedirect(request, response, kickoutUrl);
			return false;
		}
		return true;
	}

}
